<?php

  function registerPage($url) {
    global $connection;
    $url = mysql_real_escape_string($url);
    $query = "SELECT * FROM WebPage WHERE url='" . $url . "'";
    $result = mysql_query($query);
     
    if (mysql_num_rows($result) > 0) {
      return 0;
    }

    $query2 = "INSERT INTO WebPage(url) VALUES('" . $url . "')";
    $result = mysql_query($query2, $connection);
    $result = mysql_query($query, $connection);
    $result_row = mysql_fetch_assoc($result);
    $webpage_id = $result_row['id'];
    
    $of_connection = mysql_connect('localhost', 'root', 'rootpass');
    mysql_select_db("xmpp_db", $of_connection);
   
    $room_id = -1; 
    do {
      $query = "SELECT id FROM ofID where idType=23";
      $result = mysql_query($query, $of_connection);
      $result_row = mysql_fetch_assoc($result);
      $room_id = $result_row['id'];
      $next_id = $room_id + 1;

      $query = "UPDATE ofID SET id=$next_id WHERE idType=23 AND id=$room_id";
      $result = mysql_query($query, $of_connection);
    } while (!$result);

    $room_name = "room_" . $webpage_id;
    $cur_time = str_pad("" . (time() * 1000), 15, "0", STR_PAD_LEFT);
    $query = "INSERT INTO ofMucRoom(serviceID, roomID, creationDate, "
           . "modificationDate, name, naturalName, description, lockedDate, "
           . "emptyDate, canChangeSubject, maxUsers, publicRoom, moderated, "
           . "membersOnly, canInvite, roomPassword, canDiscoverJID, logEnabled, "
           . "subject, rolesToBroadcast, useReservedNick, canChangeNick, "
           . "canRegister) "
           . "VALUES(1, $room_id, '$cur_time', '$cur_time', 'room_$webpage_id', "
           . "'room_$webpage_id', 'page discussion', '000000000000000', "
           . "'$cur_time', 0, 0, 1, 0, 0, 0, NULL, 0, 0, 'page discussion', "
           . "7, 0, 1, 1)";
    mysql_query($query, $of_connection);
    mysql_select_db("metaweb_db", $of_connection);
    //return $query;

    return $webpage_id;
  }

  function getPageParameterId($webpage_id, $url_param) {
    global $connection;
    $url_param = mysql_real_escape_string($url_param);
    $query = "SELECT * FROM WebPageQuery WHERE webpage_id=$webpage_id"
           . " AND query=\"" . $url_param . "\"";
    $result = mysql_query($query, $connection);
    
    if (mysql_num_rows($result) == 0) {
      $query2 = "INSERT INTO WebPageQuery(webpage_id, query)"
             . " VALUES($webpage_id, '$url_param')";
      $result = mysql_query($query2, $connection);
      $result = mysql_query($query, $connection);
    }
    $result_row = mysql_fetch_assoc($result);
    return $result_row['id'];
  }

  function updatePageParameter($webpage_id, $url_param, $title) {
    global $connection;
    $id = getPageParameterId($webpage_id, $url_param);
     
    $query = "UPDATE WebPageQuery SET title='$title'"
           . "WHERE id=$id";
    mysql_query($query, $connection);
    return $id;
  }
 
?>
